package com.example.roomdemo.db

import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import com.example.roomdemo.app.MyApp
import com.example.roomdemo.bean.User
import com.example.roomdemo.dao.UserDao

/**
 * @author: njb
 * @date: 2023/7/15 21:47
 * @desc:
 */

@Database(entities = [User::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
    abstract fun userDao(): UserDao
}
    class RoomUtils private constructor() {

        private val database: AppDatabase by lazy {
            Room.databaseBuilder(
                MyApp.instance.applicationContext,
                AppDatabase::class.java, "app-database"
            ).build()
        }

        companion object {
            @Volatile
            private var instance: RoomUtils? = null

            fun getInstance(): RoomUtils {
                return instance ?: synchronized(this) {
                    instance ?: RoomUtils().also { instance = it }
                }
            }
        }

        private val userRepository: UserRepository by lazy {
            UserRepository(database.userDao())
        }

        suspend fun insertUser(user: User) {
            userRepository.insertUser(user)
        }

        suspend fun updateUser(user: User) {
            userRepository.updateUser(user)
        }

        suspend fun deleteUser(user: User) {
            userRepository.deleteUser(user)
        }

        suspend fun getAllUsers(): List<User> {
            return userRepository.getAllUsers()
        }

        suspend fun deleteUsers(user: List<User>) {
            return userRepository.deleteUsers(user)
        }


        suspend fun deleteAllUser() {
            userRepository.deleteAllUser()
        }
}